package com.yang.config;

import com.alibaba.fastjson.JSONObject;
import com.yang.pojo.InterfaceInfo;
import com.yang.pojo.Role;
import com.yang.pojo.UserInfo;
import com.yang.service.InterfaceInfoService;
import com.yang.service.RoleService;
import com.yang.service.UserInfoService;
import com.yang.util.JwtUtil;
import com.yang.util.ParamUtil;
import com.yang.util.ResponseKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class RoleInterceptor implements HandlerInterceptor {

	private static final Logger log = LoggerFactory.getLogger(RoleInterceptor.class);

	@Resource
	UserInfoService userInfoService;
	@Resource
	InterfaceInfoService interfaceInfoService;
	@Resource
	RoleService roleService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		Map<String, Object> map = new HashMap<>();
		try {
			response.setHeader("Content-type", "application/json;charset=UTF-8");
			String token = request.getHeader("token");
			Integer userInfoId = JwtUtil.getUserInfoId(token);
			UserInfo userInfoDB = userInfoService.findById(userInfoId);
			Role role = roleService.findById(userInfoDB.getRoleId());

			//接口调用权限控制
			String requestURI = request.getRequestURI();
			System.out.println("requestURI: "+requestURI);
			InterfaceInfo interfaceInfo = interfaceInfoService.findFirstByUri(requestURI);
			if (interfaceInfo != null) {
				Integer id = interfaceInfo.getId();
				System.out.println(id);
				String interfaceInfoIds = role.getInterfaceInfoIds().trim().replaceAll("\r", "").replaceAll("\n", "");
				System.out.println(interfaceInfoIds);
				List<Integer> idList = ParamUtil.toIntegerList(interfaceInfoIds);
				if (idList != null && idList.contains(id)) {
					//有权限访问
					return true;
				} else {
					map.put(ResponseKey.MESSAGE, "无权限访问该接口");
					map.put(ResponseKey.SUCCESS, false);
					response.getWriter().write(JSONObject.toJSONString(map));
					return false;
				}
			} else {
				map.put(ResponseKey.MESSAGE, "uri不存在");
				map.put(ResponseKey.SUCCESS, false);
				response.getWriter().write(JSONObject.toJSONString(map));
				return false;
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			map.put(ResponseKey.MESSAGE, "权限验证程序错误");
			map.put(ResponseKey.SUCCESS, false);
			response.getWriter().write(JSONObject.toJSONString(map));
			return false;
		}
	}

}
